<template>
  <component :is="tagName"
             :class="classes"
             :disabled="disabled"
             @click="handleClickLink"
             v-bind="tagProps">
    <Loading v-model="showLoading" v-if="loading"></Loading>
    <Icon :type="icon" :custom="customIcon" v-if="(icon || customIcon) && !loading"></Icon>
    <span v-if="showSlot" ref="slot"><slot></slot></span>
  </component>
</template>

<script>
import Icon from '../../icon'
import Loading from '../../loading'
import { oneOf } from '../../../utils/assist'
import mixinsLink from '../../../mixins/link'
import size from '../../../mixins/size'
const prefixCls = 'sh-btn'

export default {
  name: 'Button',
  mixins: [mixinsLink, size],
  props: {
    type: {
      validator (value) {
        return oneOf(value, ['default', 'primary', 'dashed', 'ghost', 'text', 'info', 'success', 'warning', 'error'])
      },
      default: 'default'
    },
    shape: {
      validator (value) {
        return oneOf(value, ['circle', 'circle-outline'])
      }
    },
    htmlType: {
      default: 'button',
      validator (value) {
        return oneOf(value, ['button', 'submit', 'reset'])
      }
    },
    loading: Boolean,
    disabled: Boolean,
    icon: {
      type: String,
      default: ''
    },
    customIcon: {
      type: String,
      default: ''
    },
    ghost: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      showLoading: true,
      animation: 'around',
      showSlot: true
    }
  },
  computed: {
    classes () {
      return [
        `${prefixCls}`,
        `${prefixCls}-${this.type}`,
        {
          [`${prefixCls}-${this.shape}`]: !!this.shape,
          [`${prefixCls}-${this.sizes}`]: !!this.sizes,
          [`${prefixCls}-loading`]: this.loading != null && this.loading,
          [`${prefixCls}-icon-only`]: !this.showSlot && (!!this.icon || !!this.customIcon || this.loading),
          [`${prefixCls}-ghost`]: this.ghost
        }
      ]
    },
    isHrefPattern () {
      const { to } = this
      return !!to
    },
    tagName () {
      const { isHrefPattern } = this
      return isHrefPattern ? 'a' : 'div'
    },
    tagProps () {
      const { isHrefPattern } = this
      if (isHrefPattern) {
        const { linkUrl, target } = this
        return { href: linkUrl, target }
      } else {
        const { htmlType } = this
        return { type: htmlType }
      }
    }
  },
  mounted () {
    this.showSlot = this.$slots.default !== undefined
  },
  methods: {
    handleClickLink (event) {
      if (this.disabled === false) {
        this.$emit('click', event)
      }
    }
  },
  components: {
    Icon,
    Loading
  }
}
</script>
